package c2.advanced.share;

import c2.advanced.C2Advanced;
import c2.advanced.server.configuration.SetupContext;
import cate.common.rpc.RpcReg4Game;
import cp.solution.business.cloud.CloudFaxEntity;
import cp.solution.business.game.conf.AdvancedConfigEntity;
import cp.solution.fax.FaxTags;
import cp.solution.rpc.RpcReg4Solution;
import cp.solution.rpc.bridge.FaxBridge;
import cp.solution.rpc.codec.part.ComboCodecConfiguration;
import cp.solution.rpc.template.RpcReceiverTemplate;
import cp.solution.rpc.template.RpcSenderTemplate;
import fax.client.FaxClientProperties;
import fax.client.codec.FaxBytesClientCodec;
import fax.client.util.StandardFaxSetup;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class RpcSuit {

    private RpcSenderTemplate sender;
    private RpcReceiverTemplate receiver;

    public RpcSenderTemplate send() {
        return sender;
    }

    public RpcReceiverTemplate recv() {
        return receiver;
    }

    protected abstract void handleProperties(FaxClientProperties properties, AdvancedConfigEntity conf);

    public void setup(SetupContext context) throws Exception {
        AdvancedConfigEntity conf = context.launcher.conf;
        CloudFaxEntity cloudFax = context.launcher.cloudFax;
        if(null == cloudFax) {
            log.error("cloudFax为空，无法启动!");
            C2Advanced.shutdown("null == cloudFax");
        }

        new ComboCodecConfiguration()
                .handle(RpcReg4Solution::handle)
                .handle(RpcReg4Game::handle)
                .buildAndUseCodec();

        FaxClientProperties properties = new FaxClientProperties();
        properties.setNodeHost(cloudFax.getHost());
        properties.setNodePort(cloudFax.getPort());
        properties.setReconnectInterval(5_000);
        properties.setAutoConcurrency(true);
        handleProperties(properties, conf);

        StandardFaxSetup faxSetup = new StandardFaxSetup().exe(properties, FaxBytesClientCodec.getInstance());

        //RpcRegister.setCodecTypeResolver(ConstantRpcMessageCodecTypeResolver.buildForKryo());

        this.sender = FaxBridge.buildSenderTemplate(faxSetup);
        if(context.env.isDebugShareService()) {
            this.sender.sender().setMsgHeadHandler(msgHead -> msgHead.addTag(FaxTags.TAG_DEV_MODE, FaxTags.DEV_MODE_DEBUG));
        }
        this.receiver = FaxBridge.buildReceiverTemplate(faxSetup);
    }
}
